<template>
  <div class="fullMain">
    <div class="mainbBg">
      <div>
        <!--插入验证提示框-->
        <div v-transfer-dom>
          <alert v-model="isShowAlert">{{alertText}}</alert>
        </div>
        <div>
          <div style="border: #ededed solid 1px;border-left: none;border-right: none;margin: 5px">
            <calendar
              class="times"
              :readonly="readonly"
              v-model="date"
              :title="title"
              :placeholder="placeholder"
              :show-next-month="false"
              :show-last-month="false"
              :end-date="today"
              style="height: 60px"
            ></calendar>
          </div>
          <div v-if="isShowMemory">
            <div class="groupDiv">
              <div class="chatDiv" v-for="(item,index) in reportList" :key="index">
                <!-- 普通日报的显示模板 -->
                <div v-if="item.type !== -1">
                  <div class="modifyTemp">
                    <i
                      class="fa fa-pencil-square-o"
                      @click="modifyMemory(item)"
                      style="color:red;font-size:20px;position:absolute;right:85px;"
                    ></i>
                    <i
                      class="fa fa-times"
                      @click="deleteMemory(item)"
                      style="color:red;font-size:20px;position:absolute;right:55px;"
                    ></i>
                  </div>
                  <div style="word-wrap:break-word">
                    <br />
                    {{type(item.type)}}: {{item.startTime}}--{{item.endTime}} {{item.content}}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="msgContent">
          <div class="msgBox">
            <div style="width:65%;">
              <popup-radio
                class="popupradio-custom"
                title="标签："
                :options="types"
                v-model="typeSelected"
                @on-show="getBacklogs"
                placeholder="请选择标签"
                style="height:20px;"
              ></popup-radio>
            </div>
            <!-- 非疫情的模板 -->
            <div v-show="this.typeSelected !== -1">
              <div class="timeDiv">
                <span>起始：</span>
                <div class="container" @click="clickFun_start">
                  <input id="input-start" value data-default="09:00" readonly style="width:50%;" />
                </div>
              </div>
              <div class="timeDiv">
                <span>截止：</span>
                <div class="container" @click="clickFun_end">
                  <input id="input-end" value data-default="11:45" readonly style="width:50%;" />
                </div>
              </div>
              <div class="customDiv">
                <x-textarea v-model="content" placeholder="点击输入内容" title="内容："></x-textarea>
              </div>
              <div class="customDiv">
                <x-textarea
                  style="padding:0px 0px 0px 15px;"
                  v-model="impression"
                  placeholder="点击输入感想(仅需填写一次即可)"
                  title="感想："
                ></x-textarea>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="displayFlex" style="margin-top:-30px;padding: 50px;margin-bottom: 60px">
        <button
          type="button"
          class="affirmBtn specialBtn"
          style="margin-right: 40px;"
          @click="saveTemporary"
        >新增</button>
        <button type="button" class="affirmBtn specialBtn" @click="submit">提交</button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  Calendar,
  Group,
  PopupPicker,
  PopupRadio,
  XHeader,
  XTextarea,
} from "vux";
import { mapState } from "Vuex";
import report from "api/report";
import group from "api/group";
import todo from "api/todo";
import { NumOfChineseChar } from "utilMethods/reg.js";
import "components/ClockPicker/dist/jquery-clockpicker.min.css";
import "components/ClockPicker/dist/jquery-clockpicker.min.js";
import "components/ClockPicker/dist/jquery-clockpicker.css";
import "components/ClockPicker/dist/jquery-clockpicker.js";

export default {
  name: "createReportPage",
  components: {
    XHeader,
    Group,
    Calendar,
    XTextarea,
    PopupPicker,
    PopupRadio,
  },
  data() {
    return {
      isShowAlert: false, // 是否显示验证提示框
      alertText: "",
      readonly: false,
      today: "",
      date: "",
      title: "日期选择：",
      placeholder: "",
      typeList: [],
      typeSelected: null,
      // 用于时间段的默认设置
      timeSlots: [
        { startTime: "09:00", endTime: "11:45" },
        { startTime: "14:00", endTime: "17:45" },
        { startTime: "19:00", endTime: "21:00" },
      ],
      startTime: "09:00",
      endTime: "11:45",
      isShown: false,
      //日报填写
      reportId: null,
      content: "",
      impression: "",
      reportList: [], //存放修改前的旧数据
      isShowMemory: false,
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    ...mapState(["allBacklog"]),
    //准备“标签”
    types() {
      const { allBacklog } = this;
      console.log("{allBacklog}", { allBacklog });
      const arr = [];
      let key, value;
      this.typeList.length = 0;
      {
        key = 0;
        value = "学习";
        arr.push({ key, value });
        this.typeList.push({ key, value });
      }
      {
        key = -2;
        value = "休息";
        arr.push({ key, value });
        this.typeList.push({ key, value });
      }
      if (!allBacklog) {
        return;
      }
      allBacklog.forEach((element) => {
        key = element.id;
        value = element.title;
        arr.push({ key, value });
        this.typeList.push({ key, value });
      });
      console.log("typeList", arr);
      return arr;
    },
  },
  mounted() {
    this.typeSelected = 0;
    $("#input-start").prop("value", "09:00");
    $("#input-end").prop("value", "11:45");
    this.setEditDate();
    this.clickFun_start();
    this.clickFun_end();
    this.getMinLengthOfReport();
    this.modifyInit();
  },
  methods: {
    //《《初始化相关
    //请求undo标签，存入store
    async getBacklogs() {
      const result = await todo.getTodoUndone();
      if (result.code === 0) {
        this.showAlert(result.message);
      } else {
        this.$store.commit("recordAllBacklog", result.data);
      }
    },
    //修改状态-渲染旧数据
    modifyInit() {
      this.getBacklogs();
      const repoItem = this.$route.params.repoItem;
      console.log("repoItem::", repoItem);
      if (!repoItem) {
        return;
      }
      if (!repoItem.activities) {
        return;
      }
      repoItem.activities.forEach((element) => {
        console.log("element::", element);
        let minArr = {};
        minArr = {
          startTime: element.startTime.substring(0, 5),
          endTime: element.endTime.substring(0, 5),
          type: element.type,
          content: element.content,
          imgSrc: element.imgSrc,
        };
        this.reportList.push(minArr);
      });
      this.impression = repoItem.impression;
      this.userId = repoItem.userId;
      this.date = repoItem.date;
      this.reportId = repoItem.reportId;
      this.readonly = true;
      this.isShowMemory = true;
    },
    //M:时间预处理（讲原来的setToday和setYesterday合并为一个）
    setEditDate() {
      let now = new Date();
      let year = "",
        trueMonth = "",
        day = "";
      let hour = now.getHours();
      if (hour >= 9) {
        year = now.getFullYear();
        trueMonth = now.getMonth() + 1;
        day = now.getDate();
      } else {
        // 如果在早上9点前填写日报，日期处理为前一天
        let yesterday_milliseconds = now.getTime() - 1000 * 60 * 60 * 24;
        let yesterday = new Date();
        yesterday.setTime(yesterday_milliseconds);
        year = yesterday.getFullYear();
        trueMonth = yesterday.getMonth() + 1;
        day = yesterday.getDate();
      }
      if (trueMonth < 10) trueMonth = "0" + trueMonth;
      if (day < 10) day = "0" + day;
      this.today = year + "-" + trueMonth + "-" + day;
      this.date = this.today;
      this.placeholder = this.date;
    },
    //时钟组件的自动关闭
    clickFun_start() {
      $("#input-start").clockpicker({ autoclose: true });
    },
    clickFun_end() {
      $("#input-end").clockpicker({ autoclose: true });
    },
    //》》初始化相关

    //《《填写验证相关
    startTimeCom() {
      let input_start = $("#input-start");
      input_start.attr("value", "09:00");
      return input_start.prop("value");
    },
    endTimeCom() {
      return $("#input-end").prop("value");
    },
    //M:这里换成了直接比较字符串，而不是分别比较小时和分钟
    // 比较起始时间和截止时间,A<B返回-1，A=B返回0，A>B返回1
    compareTime(start, end) {
      if (start < end) {
        return -1;
      } else if (start > end) {
        return 1;
      } else {
        return 0;
      }
    },
    //判断已填的时间段是否和自定义的时间段相符合，如果isMatch为false，有不符合的，则认为有自定义时间段.
    matchTime(savedItem) {
      console.log("savedItem", savedItem);
      for (let i = 0; i < this.timeSlots.length; i++) {
        if (
          this.compareTime(savedItem.startTime, this.timeSlots[i].startTime) ===
          0
        ) {
          return (
            this.compareTime(savedItem.endTime, this.timeSlots[i].endTime) === 0
          );
        }
      }
      return false;
    },
    //设置默认时间。如果自定义时间，则下一次默认为“”，，否则下一次默认为timeSlot
    chooseTime(savedItem) {
      console.log("chooseTime", savedItem);
      if (!this.matchTime(savedItem) || this.notChoose() === 3) {
        this.startTime = "";
        this.endTime = "";
        $("#input-start").prop("value", "");
        $("#input-end").prop("value", "");
      } else {
        this.notChoose();
      }
    },
    // 查找第一个未匹配的时间段(这部分暂时没看，也就没改)
    notChoose() {
      let numOfMatch = 0;
      let count = 1,
        length_time = this.timeSlots.length,
        length_repo = this.reportList.length,
        isMatch;
      for (let index_time = 0; index_time < length_time; ++index_time) {
        isMatch = false;
        for (let index_repo = 0; index_repo < length_repo; ++index_repo) {
          if (this.reportList[index_repo].type !== -1) {
            let compareStart = this.compareTime(
              this.reportList[index_repo].startTime,
              this.timeSlots[index_time].startTime
            );
            let compareEnd = this.compareTime(
              this.reportList[index_repo].endTime,
              this.timeSlots[index_time].endTime
            );
            if (compareStart === 0 && compareEnd === 0) {
              isMatch = true;
              ++numOfMatch;
            }
          }
        }
        if (isMatch === false && count === 1) {
          ++count;
          this.startTime = this.timeSlots[index_time].startTime;
          this.endTime = this.timeSlots[index_time].endTime;
          $("#input-start").prop("value", this.startTime);
          $("#input-end").prop("value", this.endTime);
        }
      }
      return numOfMatch;
    },
    // 判断普通日报的内容
    judge_repo(minArr) {
      let chineseCharNum = NumOfChineseChar(minArr.content);
      console.log("chineseCharNum", chineseCharNum);
      console.log("chineseCharNeeded", this.chineseCharNeeded);

      if (this.typeSelected !== -2 && chineseCharNum < this.chineseCharNeeded) {
        let need = this.chineseCharNeeded - chineseCharNum;
        this.showAlert("日报内容还需填写" + need + "字");
        return false;
      } else if (this.compareTime(minArr.startTime, minArr.endTime) === 1) {
        // 截止时间必须再起始时间之后
        this.showAlert("截止时间须在起始时间之后");
        return false;
      } else if (this.checkTime(minArr.startTime, minArr.endTime)) {
        this.showAlert("所填日报时间段不得重叠");
        return false;
      } else {
        return true;
      }
    },
    //》》填写验证相关结束

    //《《暂存相关
    //在暂存前已经进行了各部分的验证
    saveTemporary() {
      let minArr = {};
      minArr = {
        startTime: this.startTimeCom(),
        endTime: this.endTimeCom(),
        type: this.typeSelected,
        content: this.content,
        imgSrc: "",
      };
      // 对暂存内容进行验证
      if (minArr.startTime === "") {
        this.showAlert("起始时间为空");
      } else if (minArr.endTime === "") {
        this.showAlert("截止时间为空");
      } else if (this.judge_repo(minArr)) {
        this.reportList.push(minArr);
        this.isShowMemory = true;
        // 存完过后将input框中数据初始化，方便下一次填写
        this.content = "";
        this.chooseTime(minArr);
      }
    },
    deleteMemory(item) {
      const index = this.reportList.indexOf(item);
      this.reportList.splice(index, 1);
      // 让三个默认的时间和第几条记录对齐
      this.content = "";
      this.chooseTime();
    },
    //修改时删除原来的那条记录
    modifyMemory(item) {
      if (item.type === -2) {
        this.typeSelected = -2;
      }
      const index = this.reportList.indexOf(item);
      $("#input-start").prop("value", item.startTime);
      $("#input-end").prop("value", item.endTime);
      this.content = item.content;
      this.reportList.splice(index, 1);
    },
    //》》暂存相关

    //《《提交/修改相关
    async submit() {
      let minArr = {}; //存放当前编辑面板中的数据
      minArr = {
        startTime: this.startTimeCom(),
        endTime: this.endTimeCom(),
        type: this.typeSelected,
        content: this.content,
        imgSrc: "",
      };
      // 如果repoItem不为空，表示为修改日报
      if (this.$route.params.repoItem !== undefined) {
        console.log(
          "this.$route.params.repoItem::",
          this.$route.params.repoItem
        );
        this.modifyRepo(minArr);
      }
      // 如果repoItem为空，表示为填写日报
      else {
        this.editRepo(minArr);
      }
    },
    async editRepo(minArr) {
      if (
        minArr.startTime !== "" &&
        minArr.endTime !== "" &&
        minArr.content !== ""
      ) {
        if (this.judge_repo(minArr)) {
          this.reportList.push(minArr);
        } else {
          return;
        }
      }
      const result = await report.postReport({
        impression: this.impression,
        date: this.date,
        activities: this.reportList,
      });
      if (result.code === 0) {
        // 如果失败了显示提示
        this.showAlert(result.message);
      } else {
        this.showAlert("提交成功");
        setTimeout(this.back, 1000);
      }
    },
    async modifyRepo(minArr) {
      if (
        (minArr.startTime !== "") &
        (minArr.endTime !== "") &
        (minArr.content !== "")
      ) {
        if (this.judge_repo(minArr)) {
          this.reportList.push(minArr);
        } else {
          return;
        }
      }
      const result = await report.postUpdateReport({
        userId: this.userInfo.userId,
        impression: this.impression,
        date: this.date,
        reportId: this.reportId,
        activities: this.reportList,
      });
      // 获取到执行结果后，
      if (result.code === 0) {
        // 如果失败了显示提示
        this.showAlert(result.message);
      } else {
        this.showAlert("修改成功");
        setTimeout(this.back, 1000);
      }
    },
    //》》提交/修改相关

    //《《工具函数
    //将typeId转换为typeName
    type(id) {
      let type;
      this.typeList.forEach((element) => {
        if (id === element.key) {
          type = element.value;
        }
      });
      return type;
    },
    // 用于判断返回：到上一页还是退出
    pushHistory() {
      const state = {
        title: "title",
        url: this.$route.path,
      };
      console.log("pushHistory:" + this.$route.path);
      window.history.replaceState(state, "title", this.$route.path);
    },
    // 判断时间段是否有重复
    checkTime(temp_startTime, temp_endTime) {
      if (this.reportList.length === 0) {
        return false;
      } else {
        for (let i = 0; i < this.reportList.length; i++) {
          if (
            this.compareTime(temp_endTime, this.reportList[i].startTime) < 1 ||
            this.compareTime(temp_startTime, this.reportList[i].endTime) > -1
          ) {
          } else {
            return true;
          }
        }
        return false;
      }
    },
    trim(str) {
      return str.replace(/(^\s*)|(\s*$)/g, "");
    },
    async getMinLengthOfReport() {
      const result = await group.getMaxLengthOfReport();
      if (result.code === 1) {
        this.chineseCharNeeded = result.data;
        // console.log('日报字数限制',this.chineseCharNeeded)
      } else {
        this.showAlert(result.message);
      }
    },
    //》》工具函数

    //《《基础功能
    // 验证提示框
    showAlert(alertText) {
      this.isShowAlert = true;
      this.alertText = alertText;
    },
    closeTip() {
      this.isShowAlert = false;
      this.alertText = "";
    },
    back() {
      $("#input-start").clockpicker(this.isShown);
      $("#input-end").clockpicker(this.isShown);
      this.$router.go(-1);
    },
    //》》基础功能
  },
};
</script>
<style lang="less">
.weui-cells_radio {
  height: 250px;
}

.weui-cells_radio .weui-cell__bd p {
  margin: 5px;
}
</style>
